/*
 * Copyright 2013 Agustina Martinez-Garcia

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package uk.ljmu.fedoraifz.utilities;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class GeneralUtilities {

    public static final String URL_PROTOCOL = "http";
    private static Logger log = Logger.getLogger(GeneralUtilities.class);
    /**
     * 
     * @param is
     * @return
     * @throws IOException
     */
    public static String convertStreamToString(InputStream is)
    throws IOException {
	/*
	 * To convert the InputStream to String we use the
	 * BufferedReader.readLine() method. We iterate until the BufferedReader
	 * return null which means there's no more data to read. Each line will
	 * appended to a StringBuilder and returned as String.
	 */
	if (is != null) {
	    StringBuilder sb = new StringBuilder();
	    String line;

	    try {
		BufferedReader reader = new BufferedReader(
			new InputStreamReader(is, "UTF-8"));
		while ((line = reader.readLine()) != null) {
		    sb.append(line).append("\n");
		}
	    } finally {
		is.close();
	    }
	    return sb.toString();
	} else {
	    return "";
	}
    }
    /**
     * 
     * @param urlString
     * @return
     * @throws IOException 
     */
    public static String getURLcontents(String urlString) throws IOException {
	URL u;
	InputStream is = null;
	String s;
	u = new URL(urlString);
	is = u.openStream();
	s = convertStreamToString(is);

	return s;
    }
    /**
     * Retrieves the contents of a given element in an XML string
     * @param xmlContents xml string
     * @param elementName name of the element to retrieve
     * @return string contents of the xml element
     */
    public static String parseXmlElement(String xmlContents, String elementName)
    {
	String elementContents = "";
	try {
	    Document doc = DocumentHelper.parseText(xmlContents);

	    Element elem = doc.getRootElement();
	    Element myElement = elem.element(elementName);

	    if (myElement != null)
	    {
		elementContents = myElement.getText();
	    }
	} catch (DocumentException e) {
	    log.error("Error: ", e);
	}
	return elementContents;
    }
}
